package com.gl.goods.base;

import android.content.Context;
import android.view.LayoutInflater;

import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * zhangxy:RecyclerView Adapter基类
 */
public abstract class BaseRecyclerAdapter<T> extends RecyclerView.Adapter {

	protected final Context mContext;
	protected LayoutInflater mInflater;
	protected List<T> mList = new ArrayList<T>();

	public BaseRecyclerAdapter(Context context) {
		mContext = context;
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public int getItemCount() {
		return mList != null ? mList.size() : 0;
	}

	public T getItem(int position) {
		T t = null;
		if (mList != null && mList.size() > position) {
			t = mList.get(position);
		}
		return t;
	}

	public void addData(List<T> list) {
		int lastIndex = mList.size();
		if (mList.addAll(list)) {
			notifyItemRangeInserted(lastIndex, list.size());
		}
	}

	public void setData(List<T> list) {
		mList = list;
		notifyDataSetChanged();
	}

	public List<T> getData() {
		return mList == null ? (mList = new ArrayList<T>()) : mList;
	}

	public void addItem(T item) {
		mList.add(item);
		notifyDataSetChanged();
	}

	public void addItem(int position, T item) {
		mList.add(position, item);
		notifyItemInserted(position);
	}

	public void remove(int position) {
		mList.remove(position);
		notifyItemRemoved(position);

		if(position != (getData().size())){ // 如果移除的是最后一个，忽略
			notifyItemRangeChanged(position,mList.size()-position);
		}
	}

	public void swapItem(int fromPosition, int toPosition) {
		Collections.swap(mList, fromPosition, toPosition);
		notifyItemMoved(fromPosition, toPosition);
	}

	public void clear() {
		mList.clear();
		notifyDataSetChanged();
	}

	@Override
	public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
		if (mList != null && mList.size() > position) {
			onBindData(holder, position, mList.get(position));
		}
	}

	abstract protected void onBindData(RecyclerView.ViewHolder holder, int position, T data);

}